package com.rui.cn.consumer.web;

import com.baomidou.mybatisplus.plugins.Page;
import com.rui.cn.consumer.common.PasswordUtil;
import com.rui.cn.dto.JsonResult;
import com.rui.cn.dto.Pager;
import com.rui.cn.dto.RemotePage;
import com.rui.cn.entity.system.SysRole;
import com.rui.cn.entity.system.SysUser;
import com.rui.cn.entity.system.SysUserRole;
import com.rui.cn.enums.StateEnum;
import com.rui.cn.feignservice.SysRoleService;
import com.rui.cn.feignservice.SysUserRoleService;
import com.rui.cn.feignservice.SysUserService;
import com.rui.cn.util.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class UserController {
    //用户
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     *@ 描述：用户列表
     *@ 方法名：userList
     *@ 参数：[pagination, recPerPage, page, search, sortBy, order]
     *@ 返回值类型：com.rui.cn.dto.RemotePage
     *@ 创建人：[zhang]
     *@ 创建时间：2018/4/20 0020-上午 10:47
     **/
    @RequestMapping("/userList")
    public @ResponseBody  RemotePage userList(Page pagination, @RequestParam(defaultValue = "30",required = false)Integer recPerPage, @RequestParam(defaultValue = "1",required = false)Integer page,
                        String search, String sortBy, String order){
        pagination.setSize(recPerPage);
        pagination.setCurrent(page==0?1:page);
        Page<SysUser> page1=sysUserService.userList(pagination,search,sortBy,order);
        Pager pager=new Pager(pagination.getCurrent(),page1.getTotal(),pagination.getSize());
        for (SysUser U:page1.getRecords()){
            List<SysRole> roleList=sysRoleService.selectUserRole(U.getId());
            if(!roleList.isEmpty()){
                String str=roleList.stream().map(SysRole::getRoledesc).collect(Collectors.joining(","));
                U.setRoledesc(str);
            }
        }
        RemotePage<SysUser> remotePage=new RemotePage<SysUser>("success","数据加载成功",page1.getRecords(),pager);
        return  remotePage;
    }

    /**
     *@ 描述：返回用户信息
     *@ 方法名：useriframe
     *@ 参数：id
     *@ 返回值类型：ModelAndView
     *@ 创建人：[zhang]
     *@ 创建时间：2018/4/20 0020-下午 18:05
     **/
    @RequestMapping("/getuser")
    public   JsonResult getUser(Integer id){
        SysUser user=new SysUser();
        if(id !=null){
            user=sysUserService.selectById(id);
            List<SysRole> roleList=sysRoleService.selectUserRole(user.getId());
            if(!roleList.isEmpty()){
                String str=roleList.stream().map(x -> x.getId().toString()).collect(Collectors.joining(","));
                user.setRoleId(str);
            }
        }
        JsonResult jsonResult=new JsonResult(user!=null?1:0,"操作成功！",user);
        return jsonResult;
    }
    /**
     *@ 描述：新增修改用户信息
     *@ 方法名：addOrupdate
     *@ 参数：SysUser
     *@ 返回值类型：ModelAndView
     *@ 创建人：[zhang]
     *@ 创建时间：2018/4/20 0020-下午 18:05
     **/
    @RequestMapping("/addOrupdate")
    public JsonResult addOrupdate(SysUser user){
        boolean flag;
        user.setPassward(PasswordUtil.returnPass(user.getUsername(),user.getPassward()));
        if(user.getId()!=null) {
            flag = sysUserService.updateById(user);
            if(StringUtils.isNotBlank(user.getRoleId())){
                Map<String,Object> map=new HashMap<>();
                map.put("userid",user.getId());
                sysUserRoleService.deleteByMap(map);
                if(user.getRoleId().length()>1){
                    for (String s:user.getRoleId().split(",")){
                        sysUserRoleService.insert(new SysUserRole(user.getId(),Integer.valueOf(s)));
                    }
                }else {
                    sysUserRoleService.insert(new SysUserRole(user.getId(), Integer.valueOf(user.getRoleId())));
                }
            }
        }else {
            user.setCreatetime(DateUtils.getDateTimeNow());
            user.setEnable(StateEnum.ONE.getValue());
            Integer userId = sysUserService.insertMyUser(user);
            flag =!userId.equals(null)?true:false;
            if(StringUtils.isNotBlank(user.getRoleId())) {
                if(user.getRoleId().length()>1){
                    for (String s : user.getRoleId().split(",")) {
                        sysUserRoleService.insert(new SysUserRole(userId, Integer.valueOf(s)));
                    }
                }else {
                    sysUserRoleService.insert(new SysUserRole(userId, Integer.valueOf(user.getRoleId())));
                }
            }
        }
        JsonResult jsonResult=new JsonResult(flag?1:0,"操作成功！");
        return jsonResult;
    }
    /**
     *@ 描述：删除用户
     *@ 方法名：deleteUser
     *@ 参数：SysUser
     *@ 返回值类型：ModelAndView
     *@ 创建人：[zhang]
     *@ 创建时间：2018/4/20 0020-下午 18:05
     **/
    @RequestMapping("/deleteUser")
    public JsonResult deleteUser(@RequestParam("id[]") Integer id[]){
       boolean row= sysUserService.deleteBatchIds(Arrays.asList(id));
       JsonResult jsonResult=new JsonResult(row?1:0,"操作成功！");
       return jsonResult;
    }
}
